<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 2017/9/29
 * Time: 上午 8:54
 */

class EstimateController extends Controller
{
    public $Module = 'api';
    public $Controller = 'estimate';
    public $Action = 'index';
    public $UserConfig = array();

    public function __construct() {

    }

    /**
     * 评估列表
     */
    public function ListAction()
    {
        $this->Config = Config::GetConfig();
        $this->UserConfig = Cookie::GetMember('api');
        $this->LoadHelper('ApiHelper');
        $ApiHelper = new ApiHelper();
        $check = $ApiHelper->tokenCheck($this->Param);
        if(!$check['success']) ErrorMsg::ApiMsg($check['msg'], $check['code']);
        $this->LoadHelper('MemberHelper');
        $MemberHelper = new MemberHelper();
        $member_info = $MemberHelper->getMember($this->Param['uid']);
        $this->Param['page'] = $this->Param['page']?$this->Param['page']:1;
        $where = array();
        switch ($member_info['u_scope']){
            case \wodrow\models\Member::SCOPE_USER: // 用户级
                $where[] = array('=', 'et_sid', $member_info['u_id']);
                break;
            case \wodrow\models\Member::SCOPE_DP: // 部门级
                switch ($member_info['u_dp_type']){
                    case \wodrow\models\Member::DP_TYPE_DP: //部门
                        break;
                    case \wodrow\models\Member::DP_TYPE_DOT://网点 自己网点的订单
                        $where[] = array('=', 'et_br_id', $member_info['u_dp_id']);
                        break;
                    case \wodrow\models\Member::DP_TYPE_RG://大区 大区下所有网点订单
                        break;
                }
                break;
            case \wodrow\models\Member::SCOPE_COMP: // 单位级
                break;
            default :
                $where[] = array('=', 'et_sid', $member_info['u_id']);
                break;
        }
        if ($this->Param['bank_id']&&$this->Param['bank_id']>0){
            $where[] = array('=', 'et_bank', $this->Param['bank_id']);
            $where[] = array('=', 'et_status', '已评估');
        }
        $conditions = \wodrow\tools\Db::getConditions($where);
        $total = \wodrow\models\Estimate::count(
            array('conditions' => $conditions)
        );
        /**
         * @var $x \wodrow\models\Estimate[]
         */
        $x = \wodrow\models\Estimate::all(array(
            'conditions' => $conditions,
            'offset' => ($this->Param['page']-1)*$this->Param['limit'],
            'limit' => $this->Param['limit'],
            'order' => 'et_id desc',
        ));
        $data = array();
        foreach ($x as $k => $v){
            $v->getThreeValue();
            $y = $v->to_array();
            $y['et_attach'] = unserialize($y['et_attach']);
            $y['et_car_date'] = substr($y['et_car_date'], 0, 10);
//            preg_match_all("/\d+/s", $v->et_remarks, $t);
            $y['et_carprice'] = $v->et_carprice;
            $y['et_loan'] = $v->et_loan;
            $y['et_rate'] = $v->et_rate;
            $data[] = $y;
        }
        ErrorMsg::ApiMsg('ok', 0, array(
            'total' => $total,
            'page' => $this->Param['page'],
            'pagesize' => $this->Param['limit'],
            'list' => $data,
        ));
    }

    /**
     * 添加评估
     */
    public function AddAction()
    {
        $this->Config = Config::GetConfig();
        $this->LoadHelper('ApiHelper');
        $ApiHelper = new ApiHelper();
        $check = $ApiHelper->tokenCheck($this->Param);
        if(!$check['success']) ErrorMsg::ApiMsg($check['msg'], $check['code']);
        $this->LoadHelper('MemberHelper');
        $MemberHelper = new MemberHelper();
        $member_info = $MemberHelper->getMember($this->Param['uid']);
        $model = new \wodrow\models\Estimate();
        $model->et_name = $this->Param['et_name']; // 客户姓名
        $model->et_code = $this->Param['et_code']; // 客户身份证号||车架号后六位
        $model->et_car_type = $this->Param['et_car_type']; // 车辆类型
        $model->et_car_model = $this->Param['et_car_model']; // 车辆型号
        $model->et_car_fullmodel = $this->Param['et_car_fullmodel']; //具体车系
        $model->et_seat_number = $this->Param['et_seat_number']; //具体车系
        $model->et_bank = $this->Param['et_bank']; // 银行
        $model->et_car_date = $this->Param['et_car_date']; // 上牌注册日期
        $model->et_remarks = '希望车价'.$this->Param['et_carprice'].'元，贷款额'.$this->Param['et_loan'].'元，公司费率'.$this->Param['et_rate'].'%。'; // 备注，包括评多少，贷多少，公司费率
        $model->et_carprice = $this->Param['et_carprice'];
        $model->et_loan = $this->Param['et_loan'];
        $model->et_rate = $this->Param['et_rate'];
        $model->et_remarks_two = ""; // 重评备注
        $model->et_br_id = $member_info['u_dp_id']; // 网点ID
        $model->et_br_name = $member_info['u_dpname']; // 业务网点名称
        $model->et_sid = $member_info['u_id']; // 提交人ID
        $model->et_sname = $member_info['u_realname']; // 提交人
        $model->et_stime = time(); // 提交时间
        $model->et_stime_two = 0; // 重评提交时间
//        $model->et_ftime = time(); // 评估时间
//        $model->et_fid = $member_info['u_id']; // 评估人ID
        $model->et_status = '待评估';
        if($this->Param['et_car'] || $this->Param['et_plate'] || $this->Param['et_comp']) {
            // 存储路径序列化 图片
            $model->et_attach = serialize(array(
                'car' => \wodrow\tools\ArrayHelp::str2arr($this->Param['et_car']),
                'plate' => \wodrow\tools\ArrayHelp::str2arr($this->Param['et_plate']),
                'comp' => \wodrow\tools\ArrayHelp::str2arr($this->Param['et_comp']),
            ));
        }
        if (!$model->save()){
            ErrorMsg::ApiMsg('添加失败', 10001, \wodrow\tools\ArrayHelp::arr2str($model->errors->full_messages()));
        }else{
            $detail = $model->to_array();
            $detail['et_attach'] = unserialize($model->et_attach);
            $this->LoadHelper('EstimateHelper');
            $EstimateHelper = new EstimateHelper();
            $EstimateHelper->updateAttachtemp($model->et_id,$this->Param['temp_id']);
            ErrorMsg::ApiMsg('添加成功', 0, array(
                'detail' => $detail,
            ));

        }
    }

    /**
     * 修改评估
     */
    public function UpdateAction()
    {
        $this->Config = Config::GetConfig();
        $this->LoadHelper('ApiHelper');
        $ApiHelper = new ApiHelper();
        $check = $ApiHelper->tokenCheck($this->Param);
        if(!$check['success']) ErrorMsg::ApiMsg($check['msg'], $check['code']);
//        $this->LoadHelper('MemberHelper');
//        $MemberHelper = new MemberHelper();
//        $member_info = $MemberHelper->getMember($this->Param['uid']);
        /**
         * @var $model \wodrow\models\Estimate
         */
        $model = \wodrow\models\Estimate::find($this->Param['et_id']);
        $model->et_name = $this->Param['et_name']; // 客户姓名
        $model->et_code = $this->Param['et_code']; // 客户身份证号||车架号后六位
        $model->et_car_type = $this->Param['et_car_type']; // 车辆类型
        $model->et_car_model = $this->Param['et_car_model']; // 车辆型号
        $model->et_car_fullmodel = $this->Param['et_car_fullmodel']; //具体车系
        $model->et_seat_number = $this->Param['et_seat_number']; //具体车系
        $model->et_bank = $this->Param['et_bank']; // 银行
        $model->et_car_date = $this->Param['et_car_date']; // 上牌注册日期
        $model->et_remarks = '希望车价'.$this->Param['et_carprice'].'元，贷款额'.$this->Param['et_loan'].'元，公司费率'.$this->Param['et_rate'].'%。'; // 备注，包括评多少，贷多少，公司费率
        $model->et_carprice = $this->Param['et_carprice'];
        $model->et_loan = $this->Param['et_loan'];
        $model->et_rate = $this->Param['et_rate'];
        $model->et_status = '待评估';
        if($this->Param['et_car'] || $this->Param['et_plate'] || $this->Param['et_comp']) {
            // 存储路径序列化 图片
            $model->et_attach = serialize(array(
                'car' => \wodrow\tools\ArrayHelp::str2arr($this->Param['et_car']),
                'plate' => \wodrow\tools\ArrayHelp::str2arr($this->Param['et_plate']),
                'comp' => \wodrow\tools\ArrayHelp::str2arr($this->Param['et_comp']),
            ));
        }
        if (!$model->save()){
            ErrorMsg::ApiMsg('修改失败', 10001, \wodrow\tools\ArrayHelp::arr2str($model->errors->full_messages()));
        }else{
            $detail = $model->to_array();
            $detail['et_attach'] = unserialize($model->et_attach);
            ErrorMsg::ApiMsg('添加成功', 0, array(
                'detail' => $detail,
            ));
        }
    }

    /**
     * 删除评估
     */
    public function DeleteAction()
    {
        $this->Config = Config::GetConfig();
        $this->LoadHelper('ApiHelper');
        $ApiHelper = new ApiHelper();
        $check = $ApiHelper->tokenCheck($this->Param);
        if(!$check['success']) ErrorMsg::ApiMsg($check['msg'], $check['code']);

        $model = \wodrow\models\Estimate::find($this->Param['et_id']);
        if (!$model->delete()){
            ErrorMsg::ApiMsg('删除失败', 10001, \wodrow\tools\ArrayHelp::arr2str($model->errors->full_messages()));
        }else{
            $detail = $model->to_array();
            $detail['et_attach'] = unserialize($model->et_attach);
            ErrorMsg::ApiMsg('添加成功', 0, array(
                'detail' => $detail,
            ));
        }
    }

    /**
     * 重新评估
     */
    public function ResetAction()
    {
        $this->Config = Config::GetConfig();
        $this->LoadHelper('ApiHelper');
        $ApiHelper = new ApiHelper();
        $check = $ApiHelper->tokenCheck($this->Param);
        if(!$check['success']) ErrorMsg::ApiMsg($check['msg'], $check['code']);
        if(!$this->Param['et_remarks_two']) ErrorMsg::ApiMsg("重新评估备注不能为空", 10002,  array());
//        $this->LoadHelper('MemberHelper');
//        $MemberHelper = new MemberHelper();
//        $member_info = $MemberHelper->getMember($this->Param['uid']);
        /**
         * @var $model \wodrow\models\Estimate
         */
        $model = \wodrow\models\Estimate::find($this->Param['et_id']);
        if ($model->et_status == "待评估") ErrorMsg::ApiMsg("已经重新评估", 10003,  array());
        $model->et_stime_two = time();
        $model->et_remarks_two = $this->Param['et_remarks_two'];
//        $model->et_remarks = '希望车价'.$this->Param['et_carprice'].'元，贷款额'.$this->Param['et_loan'].'元，公司费率'.$this->Param['et_rate'].'%。'; // 备注，包括评多少，贷多少，公司费率
        $model->et_carprice = $this->Param['et_carprice'];
        $model->et_loan = $this->Param['et_loan'];
        $model->et_rate = $this->Param['et_rate'];
//        $model->et_status = "已评估";
        $model->et_status = '待评估';
        if (!$model->save()){
            ErrorMsg::ApiMsg('重新评估失败', 10001, \wodrow\tools\ArrayHelp::arr2str($model->errors->full_messages()));
        }else{
            $detail = $model->to_array();
            $detail['et_attach'] = unserialize($model->et_attach);
            ErrorMsg::ApiMsg('添加成功', 0, array(
                'detail' => $detail,
            ));
        }
    }

    /**
     * 评估绑定订单
     */
    public function BindcarAction()
    {
        $this->Config = Config::GetConfig();
        $this->LoadHelper('ApiHelper');
        $ApiHelper = new ApiHelper();
        $check = $ApiHelper->tokenCheck($this->Param);
        if(!$check['success']) ErrorMsg::ApiMsg($check['msg'], $check['code']);
        if(!$this->Param['order_id']) ErrorMsg::ApiMsg("订单编号不能为空", 10003,  array());
        /**
         * @var $order_cars \wodrow\models\OrderCar[]
         * @var $order_car \wodrow\models\OrderCar
         */
        $order_cars = \wodrow\models\OrderCar::find('all', array('conditions' => array("ot_oid = ?", $this->Param['order_id'])));
        if(count($order_cars)>1) ErrorMsg::ApiMsg("订单数错误", 10004,  array());
        if(count($order_cars)<1) {
            $order_car = new \wodrow\models\OrderCar();
            $order_car->ot_oid = $this->Param['order_id'];
        }
        if(count($order_cars)==1) $order_car = $order_cars[0];
        if($this->Param['estimate_id']){
            /**
             * @var $estimate \wodrow\models\Estimate
             */
            $estimate = \wodrow\models\Estimate::find($this->Param['estimate_id']);
            if(count($estimate)!==1) ErrorMsg::ApiMsg("评估数错误", 10005,  array());
            $estimate->getThreeValue();
            $order_car->ot_status = 'ok';
            $order_car->ot_dateline = NOW_TIME;
            $order_car->ot_car_pose = '二手车';
            $order_car->ot_car_type = $estimate->et_car_type;
            $order_car->ot_car_model = $estimate->et_car_model;
            $order_car->ot_assessment = $estimate->et_price;
            $order_car->ot_assess_time = date('Y-m-d',$estimate->et_ftime);
            $order_car->ot_mpac = $estimate->et_fname;
            $order_car->ot_initialrg_time = $estimate->et_car_date;
            $order_car->ot_forecat_time = date('Y-m-d',$estimate->et_stime);
            $order_car->ot_car_fullmodel = $estimate->et_car_fullmodel;
            $order_car->ot_car_seating = empty($estimate->et_seat_number)? 0 : $estimate->et_seat_number;
            $public_model =$this->LoadModel('Public');
            $car_series_row =$public_model->getOneRow('car_series','*',array('`cs_car_text` =?' =>$estimate->et_car_model));
            $order_car->ot_car_brand = $car_series_row['cs_car_brand'];
            $estimate->et_o_number = $this->Param['order_id'];
            $estimate->et_status = '已使用';
            if ($order_car->save()&&$estimate->save()){
                $this->LoadHelper('OrderHelper');
                $OrderHelper = new OrderHelper();
                $result = $OrderHelper->updateAttachestimate($this->Param['order_id'],$this->Param['estimate_id']);
                $ApiHelper->logSave('bind_card'. ($result>100?'_'.$result:''), $this->Param);
                ErrorMsg::ApiMsg("绑定成功", 0,  array(
                    'estimate' => $estimate->to_array(),
                    'order_car' => $order_car->to_array(),
                ));
                //todo:yangshile,反写oid到dyhl_attachment表
            }else{
                ErrorMsg::ApiMsg("保存错误", 10007,  array(
                    'estimate' => $estimate->errors,
                    'order_car' => $order_car->errors,
                ));
            }
        }else{
            $order_car->ot_status = 'ok';
            $order_car->ot_dateline = NOW_TIME;
            $order_car->ot_car_pose = '新车';
            if ($order_car->save()){
                ErrorMsg::ApiMsg("新车保存成功", 0,  array(
                    'order_car' => $order_car->to_array(),
                ));
            }else{
                ErrorMsg::ApiMsg("新车保存失败", 10006,  array());
            }
        }
    }

    public function TestAction()
    {

    }
}